from flask import Blueprint, render_template, request, jsonify, current_app
from applications.common.utils.validate import xss_escape
from applications.common.utils.http import success_api, fail_api
from applications.common.utils.rights import authorize
import requests, json
from applications.models import Role
admin_camera_groups = Blueprint('Cameragroups', __name__, url_prefix='/admin/camera_groups')


@admin_camera_groups.get('/')
@authorize("admin:camera_groups", log=True)
def main():
    return render_template('admin/camera_groups/main.html')


@admin_camera_groups.post('/data')
def data():
    page = 1
    page_size = 1000
    content = ''
    try:
        content = request.args['content']
    except:
        pass
    response = requests.post(url=current_app.config['EMERGENCY_URL'] + '/cameragroups',
                             headers={
                                 'Content-type': 'application/json'
                             },
                             data=json.dumps({
                                 "page": int(page) - 1,
                                 "page_size": page_size,
                                 "total_count": True,
                                 "search": content
                             }))
    data = json.loads(response.text)
    data['code'] = 0
    data['count'] = response.headers['total-count']
    data['limit'] = page_size
    data={'data':data['data']}
    return jsonify(data)


@admin_camera_groups.get('/tree')
def tree():

    page = 1
    page_size = 1000
    content = ''
    try:
        content = request.args['content']
    except:
        pass
    response = requests.post(url=current_app.config['EMERGENCY_URL'] + '/treecameras',
                             headers={
                                 'Content-type': 'application/json'
                             },
                             data=json.dumps({
                                 "page": int(page) - 1,
                                 "page_size": page_size,
                                 "total_count": True,
                                 "search": content
                             }))
    data = json.loads(response.text)
    data['code'] = 0
    data['limit'] = page_size
    data=data['data']
    res = {
        "status": {"code": 200, "message": "默认"},
        "data": data
    }
    return jsonify(res)


@admin_camera_groups.get('/add')
@authorize("admin:camera_groups:add", log=True)
def add():
    return render_template('admin/camera_groups/add.html')



@admin_camera_groups.post('/save')
def save():
    req_json = request.json
    name = xss_escape(req_json.get('name'))
    parent_id = xss_escape(req_json.get('parent_id'))
    parent_name = xss_escape(req_json.get('parent_name'))
    cameras = xss_escape(req_json.get('cameras'))
    response = add_api(name,parent_id,parent_name,[int(i) for i in cameras.split(',')])
    if response['code']==200:
        return success_api(msg="增加成功")
    else :
        return fail_api(msg=response['message'])
def add_api(name,parent_id,parent_name,cameras):
    body = {
        "name": name,
        "parent_id": int(parent_id),
        "parent_name": parent_name,
        "cameras": cameras
    }
    req = requests.post(url=current_app.config['EMERGENCY_URL'] + '/cameragroups/create', json=body).json()
    print("req",body)
    return req


@admin_camera_groups.get('/edit')
@authorize("admin:camera_groups:edit", log=True)
def edit():
    camera_groups=request.args.to_dict()

    roles = Role.query.all()
    checked_roles = []
    for r in roles:
        checked_roles.append(r.id)
    print("camera_groups",camera_groups)
    return render_template('admin/camera_groups/edit.html', camera_groups=camera_groups, roles=roles, checked_roles=checked_roles)


@admin_camera_groups.put('/update')
@authorize("admin:camera_groups:edit", log=True)
def update():
    req_json = request.json
    parent_id = xss_escape(req_json.get('parent_id'))
    cameras = xss_escape(req_json.get('cameras'))
    req_json['parent_id'] = int(parent_id)
    req_json['cameras'] = [int(i) for i in cameras.split(',')]
    req = requests.post(url=current_app.config['EMERGENCY_URL']+'/cameragroups/update', json=req_json).json()
    if req['code'] == 200:
        return success_api(msg="更新成功")
    else:
        return fail_api(msg=req['message'])


@admin_camera_groups.delete('/remove/<int:id>')
@authorize("admin:camera_groups:remove", log=True)
def remove(id):
    body = {
        "ids": [id]
    }
    req = requests.post(url=current_app.config['EMERGENCY_URL'] + '/cameragroups/delete', json=body).json()
    if req['code']==200:
        return success_api(msg="删除成功")
    else:
        return fail_api(msg=req['message'])

    # 批量删除
@admin_camera_groups.delete('/batchRemove')
@authorize("admin:gas_equip:remove", log=True)
def batch_remove():
    ids = list(map(int, request.form.getlist('ids[]')))
    body = {
        "ids": ids
    }
    req = requests.post(url=current_app.config['EMERGENCY_URL'] + '/cameragroups/delete', json=body).json()
    if req['code'] == 200:
        return success_api(msg="删除成功")
    else:
        return fail_api(msg=req['message'])